package com.pirestupppai.imagetool;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.pirestupppai.R;
import com.pirestupppai.common.Constant;
import com.pirestupppai.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import static com.pirestupppai.ui.activity.ImageEditActivity.getAssetsFileName;

public class DragView extends View {
	/**
	 *  注意float int 转换过程中出现的数据误差
	 *  bitmaps图层包括底图和贴纸图层，当layerId为0时，表示选中底图
	 */

	private Context mContext;
	private LayerSelectListener mLayerSelectListener;       // 选中图层Listener
	private SelectTypeListener mSelectTypeListener;         // 选中类型Listener

	private final int SELECT_LAYER = 0;          // 选中图层
	private final int DELETE_LAYER = 1;          // 删除图层

	private final int SELECT_TEXT = 0x12;        // 选择文字
	private final int SELECT_STICKER = 0x13;     // 选择贴纸

	private final int COMPRESS_WIDTH = 0;
	private final int COMPRESS_HEIGHT = 1;
	private int mCompressType = COMPRESS_WIDTH;   // 剩余区域的宽高比大于图片的宽高比时，宽度占满

	private List<CustomStickerModel> bitmaps;    		// 所有贴纸
	private List<CustomTextModel> customTexts;      	// 所有文字
	private CustomStickerModel curCustomSticker;        // 当前操作的贴纸
	private CustomTextModel curCustomText;          	// 当前操作的文字

	private Paint borderPaint;  // 边框Paint

	private float[] mPoints = new float[10];       // 用于保存初始化的贴纸数据经过Matrix变形后的Point
	private Matrix currentMatrix = new Matrix();   // 当前贴纸的Matrix

	private Bitmap mDeleteBitmap;
	private float mDeleteWidth, mDeleteHeight;

	private int surplusHeight;

    private String []mFontStyleFileNames;
    private Typeface mSecondTypeface;
    private Typeface mThirdTypeface;

	/**
	 * 模式 NONE：无 DRAG：拖拽. ZOOM:缩放
	 */
	private enum MODE {
		NONE, DRAG, ZOOM
	}
	private MODE mode = MODE.NONE;// 默认模式

	public DragView(Context context) {
		super(context);
		this.mContext = context;
		init();
    }

    public DragView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        this.mContext = context;
		init();
    }

    private void init() {
		bitmaps = new ArrayList<>();
		customTexts = new ArrayList<>();

		mDeleteBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_sticker_delete);
		mDeleteWidth = mDeleteBitmap.getWidth();
		mDeleteHeight = mDeleteBitmap.getHeight();

		borderPaint = new Paint();
		borderPaint.setStrokeWidth(4.0f);
		borderPaint.setColor(Color.parseColor("#000000"));
		borderPaint.setShadowLayer(Utils.dpToPx(mContext, 2.0f), 0, 0, Color.parseColor("#000000"));
		borderPaint.setAntiAlias(true);

        mFontStyleFileNames = getAssetsFileName("fonts");
        mSecondTypeface = Typeface.createFromAsset(mContext.getAssets(), mFontStyleFileNames[0]);
        mThirdTypeface = Typeface.createFromAsset(mContext.getAssets(), mFontStyleFileNames[1]);
	}

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

		// draw背景为白色
        canvas.drawColor(Color.parseColor("#FFFFFF"));

        // 画在后面的图显示在上面
        for(int i = 0; i < bitmaps.size(); i++){
			CustomStickerModel bitmap = bitmaps.get(i);
            canvas.drawBitmap(bitmap.getBitmap(), bitmap.matrix, null);
            if (curCustomSticker != null) {
				// 当前选中的图层，如果不是底图的话，则需要draw边框和删除按钮
                if ((bitmap == curCustomSticker) && (i != 0)) {

                    bitmap.matrix.mapPoints(mPoints, bitmap.originPoint);
                    canvas.drawLine(mPoints[0], mPoints[1], mPoints[2], mPoints[3], borderPaint);
                    canvas.drawLine(mPoints[2], mPoints[3], mPoints[4], mPoints[5], borderPaint);
                    canvas.drawLine(mPoints[4], mPoints[5], mPoints[6], mPoints[7], borderPaint);
                    canvas.drawLine(mPoints[6], mPoints[7], mPoints[0], mPoints[1], borderPaint);

                    canvas.drawBitmap(mDeleteBitmap, mPoints[0] - mDeleteWidth / 2, mPoints[1] - mDeleteHeight / 2, null);
                }
            }
        }

		// 画Text
		for (int i = 0; i < customTexts.size(); i++) {
			CustomTextModel customTextModel = customTexts.get(i);
            if (customTextModel.textStyle == 0) {
                customTextModel.textPaint.setTypeface(Typeface.DEFAULT);
            } else if (customTextModel.textStyle == 1) {
                customTextModel.textPaint.setTypeface(mSecondTypeface);
            } else if (customTextModel.textStyle == 2) {
                customTextModel.textPaint.setTypeface(mThirdTypeface);
            }
			canvas.drawText(customTextModel.textString, customTextModel.textMarginLeft, customTextModel.textMarginTop, customTextModel.textPaint);
			if (customTextModel == curCustomText) {
				canvas.drawLine(customTextModel.textMarginLeft - 10, customTextModel.textMarginBottom - 10,
						customTextModel.textMarginRight + 10, customTextModel.textMarginBottom - 10, borderPaint);

				canvas.drawLine(customTextModel.textMarginLeft - 10, customTextModel.textMarginBottom - 10,
						customTextModel.textMarginLeft - 10, customTextModel.textMarginTop + 10, borderPaint);
				canvas.drawLine(customTextModel.textMarginRight + 10, customTextModel.textMarginBottom - 10,
						customTextModel.textMarginRight + 10, customTextModel.textMarginTop + 10, borderPaint);
				canvas.drawLine(customTextModel.textMarginLeft - 10, customTextModel.textMarginTop + 10,
						customTextModel.textMarginRight + 10, customTextModel.textMarginTop + 10, borderPaint);

				canvas.drawBitmap(mDeleteBitmap, customTextModel.textMarginLeft - 40, customTextModel.textMarginBottom - 40, null);
			}
		}

    }

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
		if (bitmaps.size() > 0) {
            bitmaps.get(0).matrix = new Matrix();    // 整个绘制过程会多次测量，所以需要在这里初始化
			// 当前屏幕剩余高度
			surplusHeight = Constant.HEIGHT_OF_SCREEN - Constant.HEIGHT_OF_STATUSBAR
					- Utils.dpToPx(mContext, 64) - Utils.dpToPx(mContext, 85);
			if (bitmaps.get(0) != null) {
				float surplusRate = (float)Constant.WIDTH_OF_SCREEN / (float)surplusHeight;
				float pictureRate = (float)bitmaps.get(0).getBitmap().getWidth() / (float)bitmaps.get(0).getBitmap().getHeight();
				if (pictureRate > surplusRate) {
					mCompressType = COMPRESS_WIDTH;
					float scaleRate = (float)Constant.WIDTH_OF_SCREEN / (float)bitmaps.get(0).getBitmap().getWidth();
                    bitmaps.get(0).matrix.postScale(scaleRate, scaleRate);
					setMeasuredDimension(Constant.WIDTH_OF_SCREEN, Constant.WIDTH_OF_SCREEN * bitmaps.get(0).getBitmap().getHeight() / bitmaps.get(0).getBitmap().getWidth());
				} else {
					mCompressType = COMPRESS_HEIGHT;
					float scaleRate = (float)surplusHeight / (float)bitmaps.get(0).getBitmap().getHeight();
                    bitmaps.get(0).matrix.postScale(scaleRate, scaleRate);
					setMeasuredDimension(surplusHeight * bitmaps.get(0).getBitmap().getWidth() / bitmaps.get(0).getBitmap().getHeight(), surplusHeight);
				}
			} else {
				setMeasuredDimension(Constant.WIDTH_OF_SCREEN, surplusHeight);
			}
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_DOWN:  // 手指压下屏幕
				mode = MODE.DRAG;

				// 如果当前文字内容已经被全部删除，则删除当前文字view
				if ((curCustomText != null) && (curCustomText.textString.equals(""))) {
					customTexts.remove(curCustomText);
					curCustomText = null;
				}

				// 先判断文字选中相关
				int pointDeleteTextTag = -1;                        // 选中删除文字按钮的Tag

				if (curCustomText != null) {
					pointDeleteTextTag = deleteTextCheckTag(event.getX(), event.getY());
				}

				if (pointDeleteTextTag != -1) {
					mSelectTypeListener.OnSelectType(SELECT_STICKER, "" , 1, 20f, Color.BLACK);
					curCustomText = null;            
					customTexts.remove(pointDeleteTextTag);
					break;
				}
				int pointTextTag = pointStickerCheckTextTag(event.getX(), event.getY());  // 选中文字的Tag

				// 选中文字
				if (pointTextTag != -1) {
					curCustomSticker = null;                         // 选中文字的状态下，设置当前没有选中的贴纸
					curCustomText = customTexts.get(pointTextTag);
					curCustomText.startX = curCustomText.textMarginLeft;
					curCustomText.startY = curCustomText.textMarginTop;
					curCustomText.startTouchX = event.getX();
					curCustomText.startTouchY = event.getY();
					mSelectTypeListener.OnSelectType(SELECT_TEXT, curCustomText.textString, curCustomText.textStyle, curCustomText.textSize, curCustomText.textColor);
					break;
				}
				curCustomText = null;                               // 没有选中文字
				mSelectTypeListener.OnSelectType(SELECT_STICKER, "", 1, 20f, Color.BLACK);

				// 判断贴纸选中相关
				int pointDeleteStickerTag = -1;       // 选中删除贴纸按钮的Tag
				if (curCustomSticker != null) {
					pointDeleteStickerTag = deleteStickerCheckTag(event.getX(), event.getY());
				}
				if (pointDeleteStickerTag != -1) {
					curCustomSticker = null;
					mLayerSelectListener.OnLayerSelect(pointDeleteStickerTag, DELETE_LAYER);
					bitmaps.remove(pointDeleteStickerTag);
					break;
				}

				int pointStickerTag = pointStickerCheckStickerTag(event.getX(), event.getY());   // 选中贴纸的Tag
				mLayerSelectListener.OnLayerSelect(pointStickerTag, SELECT_LAYER);
				if (pointStickerTag == 0) {
					curCustomSticker = null;
					break;
				}
				curCustomSticker = bitmaps.get(pointStickerTag);
				currentMatrix.set(curCustomSticker.matrix);// 记录ImageView当前的移动位置
				curCustomSticker.matrix.set(currentMatrix);
				curCustomSticker.startPoint.set(event.getX(), event.getY());
				break;

			case MotionEvent.ACTION_POINTER_DOWN:// 当屏幕上还有触点（手指），再有一个手指压下屏幕
				if (curCustomSticker != null) {
					mode = MODE.ZOOM;
					curCustomSticker.oldRotation = rotation(event);
					curCustomSticker.startDis = distance(event);
					if (curCustomSticker.startDis > 10f) {
						curCustomSticker.midPoint = mid(event);
						currentMatrix.set(curCustomSticker.matrix);// 记录ImageView当前的缩放倍数
					}
				}
				break;

			case MotionEvent.ACTION_MOVE:// 手指在屏幕移动，该事件会不断地触发
				if (curCustomSticker != null) {
					if (mode == MODE.DRAG) {
						float dx = event.getX() - curCustomSticker.startPoint.x;// 得到在x轴的移动距离
						float dy = event.getY() - curCustomSticker.startPoint.y;// 得到在y轴的移动距离
						curCustomSticker.matrix.set(currentMatrix);// 在没有进行移动之前的位置基础上进行移动
						curCustomSticker.matrix.postTranslate(dx, dy);
					} else if (mode == MODE.ZOOM) {// 缩放与旋转
						float endDis = distance(event);// 结束距离
						curCustomSticker.rotation = rotation(event) - curCustomSticker.oldRotation;
						if (endDis > 10f) {
							float scale = endDis / curCustomSticker.startDis;// 得到缩放倍数
							curCustomSticker.matrix.set(currentMatrix);
							curCustomSticker.matrix.postScale(scale, scale, curCustomSticker.midPoint.x, curCustomSticker.midPoint.y);
							curCustomSticker.matrix.postRotate(curCustomSticker.rotation, curCustomSticker.midPoint.x, curCustomSticker.midPoint.y);
						}
					}
				}
				if (curCustomText != null) {
					float dx = event.getX() - curCustomText.startTouchX;// 得到在x轴的移动距离
					float dy = event.getY() - curCustomText.startTouchY;// 得到在y轴的移动距离
					// 初始位置 + 当前位置距初始触摸点的距离
					curCustomText.textMarginLeft = (int)(curCustomText.startX + dx);
					curCustomText.textMarginTop = (int)(curCustomText.startY + dy);
					curCustomText.textMarginRight= curCustomText.textMarginLeft + curCustomText.bounds.width();
					curCustomText.textMarginBottom = curCustomText.textMarginTop - curCustomText.bounds.height();
				}
				break;

			case MotionEvent.ACTION_UP:// 手指离开屏幕，如果是移动文字，则需要记录当前文字的开始移动位置
				if (curCustomText != null) {
					curCustomText.startX = curCustomText.textMarginLeft;
					curCustomText.startY = curCustomText.textMarginTop;
				}
				break;
			case MotionEvent.ACTION_POINTER_UP:// 有手指离开屏幕,但屏幕还有触点（手指）
				mode = MODE.NONE;
				break;
		}
		invalidate();
		return true;
	}

	/**
	 *  设置选中的图层
	 */
	public void setLayerId(int layerId) {
		curCustomSticker = bitmaps.get(layerId);
        curCustomText = null;
		invalidate();
	}

	/**
	 *  移除所有贴纸
	 */
	public void removeAllLayer() {
		bitmaps.clear();
	}

	/**
	 *  更改贴纸
	 */
	public void repleaceLayer(int index, CustomStickerModel bitmap) {
		bitmaps.set(index, bitmap);

		int customBitmapWidth = bitmap.bitmap.getWidth();
		int screenWdth = Constant.WIDTH_OF_SCREEN;
		int surplusHeight = Constant.HEIGHT_OF_SCREEN - Constant.HEIGHT_OF_STATUSBAR
				- Utils.dpToPx(mContext, 64) - Utils.dpToPx(mContext, 85);

		float scaleSize = (float)Utils.dpToPx(mContext, 100) / (float)customBitmapWidth;
		bitmaps.get(index).matrix.postScale(scaleSize, scaleSize);

		// 考虑两种模式下，图片的偏移量
		if (mCompressType == COMPRESS_WIDTH) {
			float transtLeft = ((float)screenWdth - bitmap.bitmap.getWidth() * scaleSize) / 2;
			float viewHeight = screenWdth * bitmaps.get(0).bitmap.getHeight() / bitmaps.get(0).bitmap.getWidth();
			float transtTop = (viewHeight - bitmap.bitmap.getHeight() * scaleSize) / 2;
			bitmaps.get(index).matrix.postTranslate(transtLeft, transtTop);
		} else {
			float transtLeft = ((float)screenWdth - bitmap.bitmap.getWidth() * scaleSize) / 2;
			float transtTop = ((float)surplusHeight - bitmap.bitmap.getHeight() * scaleSize) / 2;
			bitmaps.get(index).matrix.postTranslate(transtLeft, transtTop);
		}
	}

	/**
	 *  获取贴纸
	 */
	public CustomStickerModel getLayer(int index) {
		return bitmaps.get(index);
	}

	/**
	 *  获取所有贴纸
	 */
	public List<CustomStickerModel> getAllLayer() {
		return bitmaps;
	}

    /**
     *  获取所有文字
     */
    public List<CustomTextModel> getAllText() {
        return customTexts;
    }

	/**
	 *  移除所有的文字
	 */
	public void removeAllText() {
		customTexts.clear();
	}

	/**
	 *  添加文字
	 */
	public void addText() {
		curCustomSticker = null;
		CustomTextModel customText = new CustomTextModel(getMeasuredWidth(), getMeasuredHeight());
		customText.SetTextSize(Utils.dpToPx(mContext, 20f));
		customTexts.add(customText);
		curCustomText = customText;
		invalidate();
	}

	/**
	 *  添加底图
	 */
	public void addBackgroundBitmap(CustomStickerModel bitmap) {
		bitmaps.clear();
		bitmaps.add(bitmap);
	}

	/**
	 *  添加贴纸
	 */
	public void addBitmap(CustomStickerModel bitmap){
		curCustomText = null;

		int customBitmapWidth = bitmap.bitmap.getWidth();
		int screenWdth = Constant.WIDTH_OF_SCREEN;
		int surplusHeight = Constant.HEIGHT_OF_SCREEN - Constant.HEIGHT_OF_STATUSBAR
				- Utils.dpToPx(mContext, 64) - Utils.dpToPx(mContext, 85);

		float scaleSize = (float)Utils.dpToPx(mContext, 100) / (float)customBitmapWidth;
		bitmap.matrix.postScale(scaleSize, scaleSize);

		// 考虑两种模式下，图片的偏移量
		if (mCompressType == COMPRESS_WIDTH) {
			float transtLeft = ((float)screenWdth - bitmap.bitmap.getWidth() * scaleSize) / 2;
			float viewHeight = screenWdth * bitmaps.get(0).bitmap.getHeight() / bitmaps.get(0).bitmap.getWidth();
			float transtTop = (viewHeight - bitmap.bitmap.getHeight() * scaleSize) / 2;
			bitmap.matrix.postTranslate(transtLeft, transtTop);
		} else {
			float transtLeft = ((float)screenWdth - bitmap.bitmap.getWidth() * scaleSize) / 2;
			float transtTop = ((float)surplusHeight - bitmap.bitmap.getHeight() * scaleSize) / 2;
			bitmap.matrix.postTranslate(transtLeft, transtTop);
		}
		bitmaps.add(bitmap);
		curCustomSticker = bitmap;
	}

	// 获取将要保存的bitmap
	public Bitmap getBitmap() {
		int width = this.getWidth();
		int height = this.getHeight();
		// 创建一个bitmap
		Bitmap newb = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
		// 将该图片作为画布
		Canvas canvas = new Canvas(newb);

		for (int i = 0; i < bitmaps.size(); i++) {
			CustomStickerModel bitmap = bitmaps.get(i);

			// 保存
			canvas.save(Canvas.ALL_SAVE_FLAG);

			canvas.drawBitmap(bitmap.bitmap, bitmap.matrix, null);

			// 还原画布
			canvas.restore();
		}

		for (int i = 0; i < customTexts.size(); i++) {
			CustomTextModel CustomTextModel = customTexts.get(i);
			canvas.drawText(CustomTextModel.textString, CustomTextModel.textMarginLeft, CustomTextModel.textMarginTop, CustomTextModel.textPaint);
		}

		return newb;
	}

	// 获得触摸点所属Text的编号
	private int pointStickerCheckTextTag(float x, float y) {
		if (curCustomText != null) {
			if (pointTextCheck(curCustomText, x, y)) {
				for (int i = 0; i < customTexts.size(); i++) {
					if (customTexts.get(i) == curCustomText) {
						return i;
					}
				}
			}
		}

		for (int i = 0; i < customTexts.size(); i++) {
			if(pointTextCheck(customTexts.get(i), x, y)){
				return i;
			}
		}

		return -1;
	}

	// 检查触摸点是否在Text内
	private boolean pointTextCheck(CustomTextModel customText, float touchX, float touchY) {
		if (touchX >= customText.textMarginLeft && touchX <= customText.textMarginRight && touchY >= customText.textMarginBottom && touchY <= customText.textMarginTop) {
			return true;
		}
		return false;
	}

	// 获得触摸点所属Text删除按钮的编号
	private int deleteTextCheckTag(float x, float y) {
		for (int i = 0; i < customTexts.size(); i++) {
			if(deleteTextCheck(customTexts.get(i), x, y)){
				return i;
			}
		}
		return -1;
	}

	// 检查触摸点是否在Text删除按钮内
	private boolean deleteTextCheck(CustomTextModel CustomTextModel, float x, float y) {
		int checkDis = (int) Math.sqrt(Math.pow(x - CustomTextModel.textMarginLeft, 2) + Math.pow(y - CustomTextModel.textMarginBottom, 2));

		if (checkDis < 40) {
			return true;
		}
		return false;
	}

	// 获得触摸点所属Sticker的编号
	private int pointStickerCheckStickerTag(float x, float y) {
		// 如果点击区域是在当前bitmap，则移动当前bitmap
		if (curCustomSticker != null) {
			if (pointStickerCheck(curCustomSticker, x, y)) {

				for (int i = bitmaps.size() - 1; i > 0; i--) {
					if (bitmaps.get(i) == curCustomSticker) {
						return i;
					}
				}
			}
		}

		for (int i = bitmaps.size() - 1; i > 0; i--) {
			if(pointStickerCheck(bitmaps.get(i), x, y)){
				return i;
			}
		}

		return 0;
	}

	// 检查触摸点是否在Sticker内
	private boolean pointStickerCheck(CustomStickerModel bitmap, float x, float y) {
		float[] points = new float[10];
		bitmap.matrix.mapPoints(points, bitmap.originPoint);
		float x1 = points[0];
		float y1 = points[1];
		float x2 = points[2];
		float y2 = points[3];

		float x3 = points[4];
		float y3 = points[5];
		float x4 = points[6];
		float y4 = points[7];

//		float edge = (float) Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));

		float edge = (float) Math.sqrt(Math.pow(x1 - x3, 2) + Math.pow(y1 - y3, 2));

		double cal = Math.sqrt(Math.pow(x - x1, 2) + Math.pow(y - y1, 2))
				+ Math.sqrt(Math.pow(x - x2, 2) + Math.pow(y - y2, 2))
				+ Math.sqrt(Math.pow(x - x3, 2) + Math.pow(y - y3, 2))
				+ Math.sqrt(Math.pow(x - x4, 2) + Math.pow(y - y4, 2));

//		double calEdge = 2 * ( Math.sqrt(Math.pow(( x1 - x3 ), 2) + Math.pow((y1 - y3), 2)));
		double calEdge = (2 + Math.sqrt(2)) * edge;
//		if (calEdge >= cal) {
//			return true;
//		}
//		return false;

		RectF rectF = new RectF();
		bitmap.matrix.mapRect(rectF, bitmap.originRectF);
		if (rectF.contains( x, y)) {
			return true;
		}
		return  false;
	}

	// 获得触摸点所属Sticker删除按钮的编号
	private int deleteStickerCheckTag(float x, float y) {
		for (int i = 0; i < bitmaps.size(); i++) {
			if(deleteStickerCheck(bitmaps.get(i), x, y)){
				return i;
			}
		}
		return -1;
	}

	// 检查触摸点是否在Sticker删除按钮内
	private boolean deleteStickerCheck(CustomStickerModel bitmap, float x, float y) {
		float[] points = new float[10];
		bitmap.matrix.mapPoints(points, bitmap.originPoint);
		float x1 = points[0];
		float y1 = points[1];

		int checkDis = (int) Math.sqrt(Math.pow(x - x1, 2) + Math.pow(y - y1, 2));

		if (checkDis < 40) {
			return true;
		}
		return false;
	}

	/**
	 * 计算两点之间的距离
	 *
	 * @param event
	 * @return
	 */
	public float distance(MotionEvent event) {
		float dx = event.getX(1) - event.getX(0);
		float dy = event.getY(1) - event.getY(0);
		return (float) Math.sqrt(dx * dx + dy * dy);
	}

	/**
	 * 计算两点之间的中间点
	 *
	 * @param event
	 * @return
	 */
	public PointF mid(MotionEvent event) {
		float midX = (event.getX(1) + event.getX(0)) / 2;
		float midY = (event.getY(1) + event.getY(0)) / 2;
		return new PointF(midX, midY);
	}

	public float rotation(MotionEvent event) {
		double delta_x = (event.getX(0) - event.getX(1));
		double delta_y = (event.getY(0) - event.getY(1));
		double radians = Math.atan2(delta_y, delta_x);
		return (float) Math.toDegrees(radians);

	}

	public void setLayerListener(LayerSelectListener layerListener) {
		this.mLayerSelectListener = layerListener;
	}

	public void setSelectTypeListener(SelectTypeListener selectTypeListener) {
		this.mSelectTypeListener = selectTypeListener;
	}

	/**
	 *  选中图层接口
	 */
	public interface LayerSelectListener {
		void OnLayerSelect(int layerId, int type);
	}

	/**
	 *  当前操作的是文字还是贴纸接口
	 */
	public interface SelectTypeListener {
		void OnSelectType(int selectType, String textStr, int textStyle, float textSize, int textColor);
	}

	/**
	 *  改变选中的文字内容
	 */
	public void ChangeText(String textString) {
		for (int i = 0; i < customTexts.size(); i++) {
			CustomTextModel customTextModel = customTexts.get(i);
			curCustomText.textString = textString;
			if (customTextModel == curCustomText) {
				customTextModel.textString = textString;
				customTextModel.SetTextContent();
			}
		}
		invalidate();
	}

	/**
	 *  改变选中的文字样式
	 */
	public void ChangeTextStyle(int textStyle) {
		for (int i = 0; i < customTexts.size(); i++) {
			CustomTextModel customTextModel = customTexts.get(i);
			curCustomText.textStyle = textStyle;
			if (customTextModel == curCustomText) {
				customTextModel.textStyle = textStyle;
				customTextModel.SetTextContent();
			}
		}
		invalidate();
	}

	/**
	 *  改变选中文字的大小
	 */
	public void ChangeTextSize(float textSize) {
		for (int i = 0; i < customTexts.size(); i++) {
			CustomTextModel customTextModel = customTexts.get(i);
			curCustomText.SetTextSize(textSize);
			if (customTextModel == curCustomText) {
				customTextModel.SetTextSize(textSize);
			}
		}
		invalidate();
	}

	/**
	 *  改变选中文字的颜色
	 */
	public void ChangeTextColor(int textColor) {
		for (int i = 0; i < customTexts.size(); i++) {
			CustomTextModel customTextModel = customTexts.get(i);
			curCustomText.SetTextColor(textColor);
			if (customTextModel == curCustomText) {
				customTextModel.SetTextColor(textColor);
			}
		}
		invalidate();
	}

}
